#include "login.h"
#include "ui_login.h"
#include "registerdialog.h"

login::login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::login)
    , socketManager(new SocketManager(this)) // 初始化 SocketManager 对象
{
    ui->setupUi(this);
    // 触发重置按钮的信号槽连接
    connect(ui->btn_clear, SIGNAL(clicked()), this, SLOT(on_btn_clear_clicked()));
    // 触发登录按钮的信号槽连接
    connect(ui->btn_login, SIGNAL(clicked()), this, SLOT(on_btn_login_clicked()));
    connect(this, SIGNAL(close_window()), this, SLOT(close()));
    // 连接打开注册页面按钮的槽
    connect(ui->btn_register, &QPushButton::clicked, this, &login::openRegisterDialog);
    // 连接 SocketManager 的信号与槽
    connect(socketManager, &SocketManager::dataReceived, this, &login::onReadyRead);
    connect(socketManager, &SocketManager::connectionFailed, this, &login::onConnectionFailed);

    // 加载并信任 CA 证书
    socketManager->loadCaCertificate("F:/Desktop/lib/ca.crt");
}

login::~login()
{
    delete ui;
}

// 登录事件
void login::on_btn_login_clicked()
{
    // 获取 UI 登录界面的登录信息
    QString username = ui->nameEdit->text();
    QString password = ui->pwdEdit->text();
    // 检查输入框是否为空
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "错误", "所有字段均为必填!");
        return;
    }
    user = username;

    // 连接到服务器
    socketManager->connectToServer("111.231.80.52", 8934);

    // 格式化发送的数据为 "username password"
    QByteArray data = (username + " " + password).toUtf8();
    // 发送登录信息
    socketManager->sendData(data);
}

void login::onReadyRead(const QByteArray &data)
{
    QString response(data);
    // 根据响应判断登录是否成功
    if (response.trimmed() == "Login Success") {
        emit loginSuccessful();
    } else {
        // 登录失败逻辑处理
        QMessageBox::warning(this, "登录失败", "用户名或密码错误");
    }
}

void login::on_btn_clear_clicked()
{
    ui->nameEdit->clear();
    ui->pwdEdit->clear();
}

void login::openRegisterDialog()
{
    registerdialog registerDialog;
    registerDialog.exec(); // 以模态方式显示注册对话框
}

// 密码输入完成后回车触发登录事件
void login::on_pwdEdit_editingFinished()
{
    on_btn_login_clicked();
}

void login::onConnectionFailed(const QString &errorMessage)
{
    QMessageBox::warning(this, "连接失败", errorMessage);
}
